<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2020/07/13 17:57
 * Desc: 会员注册/登录公用方法
 */
class Model_Api_V2_Member_Login extends ORM
{

    /**
     * @function 登陆信息处理及数据返回
     * @param $member
     * @return array
     */
    public static function login_init($member)
    {
        $token = Common::authcode($member['mid'] . '||' . $member['pwd'], '');

        //写入Cookie_Session
        if ($member)
        {
            //写登录信息
            $user = empty($member['email']) ? $member['mobile'] : $member['email'];

            //昵称
            if (empty($member['nickname']) && !empty($user))
            {
                $memberInfo['nickname'] = substr_replace($user, '****', floor(strlen($user) / 2) - 2, 4);
            }

            //没有会员图片
            if (empty($member['litpic']))
            {
                $memberInfo['litpic'] = Common::nopic();
            }
            else
            {
                $memberInfo['litpic'] = Model_Api_V2_System::uniapp_img($member['litpic']);
            }

            // 保存登陆时间
            Model_Member::save_login_time($member['mid']);

            $jifen = Model_Jifen::reward_jifen('sys_member_login', $member['mid']);
            if ($jifen)
            {
                $content = "登录获得{$jifen}积分";
                St_Product::add_jifen_log($member['mid'], $content, $jifen, 2);
            }

            // 判断是否安装移动裂变分销
            if(St_Functions::is_normal_app_install('mobiledistribution'))
            {
                $userFxCode = DB::select('fxcode')->from('fenxiao')->where('memberid','=',$member['mid'])->and_where('status','=',1)->execute()->current();
                $memberInfo['fxcode'] = $userFxCode['fxcode'] ;
            }
            $rank = Model_Member::get_member_rank($member['mid'], array('return' => 'all'));
            $member['rank']      = $rank['current'];
            $member['rank_name'] = $rank['rankname'];
        }

        if ($member) {
            unset($member['pwd']);
        }
        return array('token'=>$token,'memberInfo'=> $member);
    }

    /**
     * @function 发送快速登录信息
     * @param $phone
     * @return array
     */
    public static function send_quick_code($phone)
    {
        $member = Model_Member::member_find($phone);
        if (empty($member))
        {
            $data = array('msg' => __("error_user_noexists"), 'status' => false);
            return $data;
        }
        $code = rand(1000, 9999);
        $send_time_key = 'quick_login_send_time'.$phone;
        $quick_login_send_time = Model_Api_V2_Common::cache('get',$send_time_key);
        if($quick_login_send_time)
        {
            $send_time=intval($quick_login_send_time);
            //频繁发送检查
            if((time()-$send_time)<=120)
            {
                $data = array('msg' => __("error_send_quick_msgcode"), 'status' => false,"data"=> array('type'=>1));
                return $data;
            }
        }
        $send_key = 'quick_login_send'.$phone;
        $send_code_key = 'quick_login_send_code'.$phone;
        Model_Api_V2_Common::cache('set',$send_key,1);
        Model_Api_V2_Common::cache('set',$send_code_key,$code);
        Model_Api_V2_Common::cache('set',$send_time_key,time());
        $status= (object)array('Success'=>true) or $status = json_decode(St_SMSService::send_member_msg($phone,NoticeCommon::MEMBER_QUICK_LOGIN_CODE_MSGTAG,"","",$code));
        if($status->Success)
        {
            $send_key = 'quick_login_send'.$phone;
            $send_code_key = 'quick_login_send_code'.$phone;
            Model_Api_V2_Common::cache('set',$send_key,1);
            Model_Api_V2_Common::cache('set',$send_code_key,$code);
            Model_Api_V2_Common::cache('set',$send_time_key,time());
            $data['status'] = true;
            $data['msg'] = "发送成功";
            //后期需删除
            $data['code'] = $code;
        }else{
            $data['status'] = false;
            $data['msg']    = $status->Message;
        }
        return $data;
    }


    /**
     * @function 短信快速登录检查
     * @param $phone
     * @param $sms_code
     * @return array
     */
    public static function sms_quick_login_check($phone,$sms_code)
    {
        $send_time_key = 'quick_login_send_time'.$phone;
        $send_key = 'quick_login_send'.$phone;
        $send_code_key = 'quick_login_send_code'.$phone;
        //检测用户是否存在
        $member = Model_Member::member_find($phone);
        if (empty($member))
        {
            $data = array('msg' => __("error_user_noexists"), 'status' => false);
            return $data;
        }
        //动态码为空
        if(!$sms_code)
        {
            $data = array('msg' => __("error_msg_not_empty"), 'status' => false);
            return $data;
        }

        $quick_login_send_code = Model_Api_V2_Common::cache('get',$send_code_key);
        //动态码不正确
        if(!$quick_login_send_code||$sms_code!=$quick_login_send_code)
        {
            $data = array('msg' => __("error_msgcode"),'status' => false);
            return $data;
        }

        $quick_login_send_time = Model_Api_V2_Common::cache('get',$send_time_key);
        $send_time=intval($quick_login_send_time);
        //时效检验
        if(time()>($send_time+15*60))
        {
            $data = array('msg' => __("error_overtime_msgcode"), 'status' => false);
            return $data;
        }

        Model_Api_V2_Common::cache('set',$send_key,null);
        Model_Api_V2_Common::cache('set',$send_code_key,null);
        Model_Api_V2_Common::cache('set',$send_time_key,null);
        $data['status'] = true;
        $data['member'] = $member;
        return $data;
    }

    /**
     * 登录状态下,第三方绑定
     * @param $data
     */
    public static function third_login_bind($data)
    {
        $supplyThird = array(
            'qq' => array(
                'alias' => 'qq',
                'name' => '腾讯QQ'
            ),
            'weixin' => array(
                'alias' => 'wx',
                'name' => '微信'
            ),
            'weibo' => array(
                'alias' => 'wb',
                'name' => '新浪微博'
            )
        );
        $rs = DB::select()->from('member_third')->where("`come_from`= '{$data['come_from']}' and openid='{$data['openid']}'")->execute()->current();
        if (empty($rs))
        {
            $third['mid'] = $data['mid'];
            $third['openid'] = preg_replace('~(.*?)\.[0-9]+$~', '$1', $data['openid']);
            $third['come_from'] = $data['come_from'] ? $data['come_from'] : '';
            $third['nickname'] = St_String::wx_nickname_filter($data['nickname']);
            $third['wx_openid'] = $data['wx_openid'] ? $data['wx_openid'] : '';
            Model_Api_V2_Common::st_insert('member_third', $third);

            $jifen_label = '';
            switch ($data['come_from'])
            {
                case 'qq':
                    $jifen_label = 'sys_member_bind_qq';
                    break;
                case 'weixin':
                    $jifen_label = 'sys_member_bind_weixin';
                    break;
                case 'weibo':
                    $jifen_label = 'sys_member_bind_sina_weibo';
                    break;
            }
            $jifen = Model_Jifen::reward_jifen($jifen_label, $data['mid']);
            if (!empty($jifen))
            {
                St_Product::add_jifen_log($data['mid'], "绑定{$supplyThird[$rs['come_from']]['name']}送积分{$jifen}", $jifen, 2);
            }

            return array(
                'status'=> true,
                'msg'=> "已绑定到{$supplyThird[$rs['come_from']]['name']}@{$rs['nickname']}"
            );
        }
        else
        {
            return array(
                'status'=> true,
                'msg'=> "已绑定到{$supplyThird[$rs['come_from']]['name']}@{$rs['nickname']}"
            );
        }
    }

    /**
     * 用户登录后信息处理
     * @param $user
     * @param bool|false $isadd 是否是新增用户
     */
    public static function write_login_info($user, $isadd = false)
    {
        $time = time();
        if ($isadd)
        {
            //增加积分记录
            $jifen = Model_Jifen::reward_jifen('sys_member_register', $user['mid']);
            if (!empty($jifen))
            {
                St_Product::add_jifen_log($user['mid'], "注册赠送积分{$jifen}", $jifen, 2);
            }
        }

        //积分日志
        //登录信息
        $update['logintime'] = $time;
        $update['loginip'] = $user['loginip'] ? $user['loginip'] : Common::get_ip();
        //如是获取不了IP,则直接赋值为空
        $update['loginip'] = $update['loginip'] ? $update['loginip'] : '';

        $userinfo = Model_Api_V2_Common::st_query('member', "mid={$user['mid']}", '*', true);
        // 第三方登录的时候不要生成密码
        $update['pwd'] = empty($userinfo['pwd']) ? '': $userinfo['pwd'];
        Model_Api_V2_Common::st_update('member', $update, "mid={$user['mid']}");
    }


    /**
     * 第三方登录账号绑定
     * @param $post
     * @return mixed|string
     */
    static function third_bind($post)
    {
        $supplyThird = array(
            'qq' => array(
                'alias' => 'qq',
                'name' => '腾讯QQ'
            ),
            'weixin' => array(
                'alias' => 'wx',
                'name' => '微信'
            ),
            'weibo' => array(
                'alias' => 'wb',
                'name' => '新浪微博'
            )
        );
        $rs['bool'] = false;
        $third = $post['third'];
        $data['nickname'] = St_String::wx_nickname_filter($third['nickname']);
        $data['loginip'] = $_SERVER['REMOTE_ADDR'];
        $data['litpic'] = $third['litpic'];
        $third_data['come_from'] = $third['come_from'] ? $third['come_from'] : '';
        $third_data['openid'] = $third['openid'];
        $third_data['nickname'] = $data['nickname'];
        $third_data['wx_openid'] = $third['wx_openid'];
        $member = isset($post['member']) ? Common::remove_xss($post['member']) : null;
        if (!is_null($member) && isset($member['user']) && isset($member['pwd']))
        {
            //已有账号绑定
            $type = strpos($member['user'], '@') ? 'email' : 'mobile';
            $pwd = $member['pwd_coded'] ? $member['pwd'] : md5($member['pwd']);
            $memberInfo = Model_Api_V2_Common::st_query('member', "{$type}='{$member['user']}' and pwd='{$pwd}'", '*', true);
            if (!empty($memberInfo))
            {
                $rs['bool'] = true;
                $data['mid'] = $memberInfo['mid'];
            }
            else
            {
                $rs['msg'] = '账号或密码不正确';
            }
            //是否绑定对应的第三方账号
            if ($rs['bool'])
            {
                $isThird = Model_Api_V2_Common::st_query('member_third', "`come_from`='{$third['come_from']}' and mid={$data['mid']}", '*', true);
                if (!empty($isThird))
                {
                    $rs['bool'] = false;
                    $rs['msg'] = "已绑定到{$supplyThird[$third['come_from']]['name']}@{$isThird['nickname']}";
                }
            }
        }
        else
        {
            //查询openid是否存在
            $third['openid'] = preg_replace('~(.*?)\.[0-9]+$~', '$1', $third['openid']);
            $isThird = Model_Api_V2_Common::st_query('member_third', "`come_from`='{$third['come_from']}' and openid='{$third['openid']}'", '*', true);
            if (empty($isThird))
            {
                $data['jointime'] = time();

                $result = Model_Api_V2_Common::st_insert('member', $data);
                if ($result[1] > 0)
                {
                    $rs['bool'] = true;
                    $data['mid'] = $result[0];
                    //三方微信,手机pc未知
                    if($third['come_from']=='weixin')
                    {
                        Model_Member::add_reg_from($data['mid'],3);
                    }
                    else if($third['come_from']=='qq')
                    {
                        Model_Member::add_reg_from($data['mid'],5);
                    }
                    else if($third['come_from']=='weibo')
                    {
                        Model_Member::add_reg_from($data['mid'],6);
                    }
                }
            }
            else
            {
                $rs['msg'] = '该账号已绑定';
            }
        }

        //登录成功
        if ($rs['bool'])
        {
            $rs['bool'] = false;
            $third_data['mid'] = $data['mid'];
            $result = Model_Api_V2_Common::st_insert('member_third', $third_data);
            if ($result[1] > 0)
            {
                $rs['bool'] = true;
                self::write_login_info($data, true);
            }
        }
        return json_encode($rs);
    }
}